<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\OfficialMessageService;
use app\AdminController;
use app\admin\validate\OfficialMessage as OfficialMessageValidate;
use think\exception\ValidateException;

/**
 * 官方消息
 * Class Officialmessage
 * @package app\admin\controller
 */
class Officialmessage extends AdminController
{
    /**
     * 官方消息列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (request()->isPost()) {
            $where = [];
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['desc', 'like', '%' . $keywords . '%'];
            }

            // 状态搜索
            $status = $this->request->param('status', '-1');
            if ($status != '-1') {
                $where[] = ['status', '=', $status];
            }

            $list = OfficialMessageService::getOfficialMessageList($where, $this->page, $this->pagesize);
            $count = OfficialMessageService::countOfficialMessageList($where);

            return adminResponseJson(['list' => $list, 'count' => $count]);
        }

        return view();
    }

    /**
     * 添加官方消息
     * @return \think\response\View
     */
    public function officialMessageAdd()
    {
        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(OfficialMessageValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (!$data['uids']) {
                $data['uids'] = '*';
            }

            OfficialMessageService::createOfficialMessage($data);

            $this->success(adminJsonMsg(1004), (STRING)url('/officialmessage/index'));
        }

        return view();
    }

    /**
     * 状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $field = trim($this->request->param('field', 'status'));

        $where = ['id' => $id];
        $info = OfficialMessageService::findOfficialMessage($where);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $result = OfficialMessageService::updateOfficialMessage([
            $field => $info[$field] == 1 ? 0 : 1,
            'update_time' => time(),
        ], $where);

        if (!$result) {
            $this->error(adminJsonMsg(1003));
        }

        $this->success(adminJsonMsg(1004));
    }
}